//
//  BZDatePicker.m
//  BZBaseWidget
//
//  Created by 郭艺伟 on 2017/10/12.
//  Copyright © 2017年 quheng. All rights reserved.
//

#import "BZDatePicker.h"
#import <Masonry/Masonry.h>

static const CGFloat CODatePickerCellHeight = 40.0;

/**
 *  重写的UIPickerView,主要对选中区域进行重绘
 */
@interface DatePickerView : UIPickerView

@property (nonatomic) BZDatePickerMode datePickerMode;

@end

@implementation DatePickerView

- (id)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
    }
    
    return self;
}

- (void)drawRect:(CGRect)rect {
    
    UIColor *normalColor = [UIColor colorWithRed:84.0/255.0 green:180.0/255.0 blue:204.0/238.0 alpha:1];
    
    //上边线
    UIView *line1 = [[self subviews] objectAtIndex:1];
    [line1 setBackgroundColor:normalColor];
    
    //下边线
    UIView *line2 = [[self subviews] objectAtIndex:2];
    [line2 setBackgroundColor:normalColor];
    
    //蓝色背景
    UIView *blueView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, CODatePickerCellHeight)];
    blueView.backgroundColor = [UIColor colorWithRed:236.0/255.0 green:249.0/255.0 blue:255.0/255.0 alpha:0.2];
    //    blueView.alpha = 0.7;
    [self addSubview:blueView];
    [blueView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(line1.mas_bottom).with.offset(0);
        make.bottom.equalTo(line2.mas_top).with.offset(0);
        make.leading.equalTo(self.mas_leading).with.offset(0);
        make.trailing.equalTo(self.mas_trailing).with.offset(0);
    }];
    
    //年
    UILabel *yearLbl;
    yearLbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 30, CODatePickerCellHeight)];
    yearLbl.textColor = normalColor;
    yearLbl.textAlignment = NSTextAlignmentCenter;
    yearLbl.text = @"年";
    //月
    UILabel *monthLbl;
    monthLbl = [[UILabel alloc]initWithFrame:CGRectMake(120, 5, 30, CODatePickerCellHeight)];
    monthLbl.textColor = normalColor;
    monthLbl.textAlignment = NSTextAlignmentCenter;
    monthLbl.text = @"月";
    //天
    UILabel *dayLbl;
    dayLbl = [[UILabel alloc]initWithFrame:CGRectMake(185, 5, 30, CODatePickerCellHeight)];
    dayLbl.textColor = normalColor;
    dayLbl.textAlignment = NSTextAlignmentCenter;
    dayLbl.text = @"日";
    //时
    UILabel *hourLbl;
    hourLbl = [[UILabel alloc]initWithFrame:CGRectMake(265, 5, 30, CODatePickerCellHeight)];
    hourLbl.textColor = normalColor;
    hourLbl.textAlignment = NSTextAlignmentCenter;
    hourLbl.text = @"时";
    //分
    UILabel *minuteLbl;
    minuteLbl = [[UILabel alloc]initWithFrame:CGRectMake(320, 5, 30, CODatePickerCellHeight)];
    minuteLbl.textColor = normalColor;
    minuteLbl.textAlignment = NSTextAlignmentCenter;
    minuteLbl.text = @"分";
    
    switch (self.datePickerMode) {
        case COCDatePickerModeYearMonth: {
            [blueView addSubview:yearLbl];
            [yearLbl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(blueView.mas_centerY).with.offset(0);
                make.leading.equalTo(self.mas_leading).with.offset(self.frame.size.width* 0.46);
            }];
            [blueView addSubview:monthLbl];
            [monthLbl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(blueView.mas_centerY).with.offset(0);
                make.leading.equalTo(self.mas_leading).with.offset(self.frame.size.width* 0.62);
            }];
            break;
        }
            //时分
        case COCDatePickerModeTime: {
            [blueView addSubview:hourLbl];
            [hourLbl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(blueView.mas_centerY).with.offset(0);
                make.leading.equalTo(self.mas_leading).with.offset(self.frame.size.width* 0.43);
            }];
            [blueView addSubview:minuteLbl];
            [minuteLbl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(blueView.mas_centerY).with.offset(0);
                make.leading.equalTo(self.mas_leading).with.offset(self.frame.size.width* 0.64);
            }];
            break;
        }
            //年月日
        case COCDatePickerModeDate: {
            [blueView addSubview:yearLbl];
            [yearLbl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(blueView.mas_centerY).with.offset(0);
                make.leading.equalTo(self.mas_leading).with.offset(self.frame.size.width* 0.33);
            }];
            [blueView addSubview:monthLbl];
            [monthLbl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(blueView.mas_centerY).with.offset(0);
                make.leading.equalTo(self.mas_leading).with.offset(self.frame.size.width* 0.53);
            }];
            [blueView addSubview:dayLbl];
            [dayLbl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(blueView.mas_centerY).with.offset(0);
                make.leading.equalTo(self.mas_leading).with.offset(self.frame.size.width* 0.77);
            }];
            break;
        }
            //年月日时分
        case COCDatePickerModeDateAndTime: {
            [blueView addSubview:yearLbl];
            [yearLbl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(blueView.mas_centerY).with.offset(0);
                make.leading.equalTo(self.mas_leading).with.offset(self.frame.size.width* 0.18);
            }];
            [blueView addSubview:monthLbl];
            [monthLbl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(blueView.mas_centerY).with.offset(0);
                make.leading.equalTo(self.mas_leading).with.offset(self.frame.size.width* 0.34);
            }];
            [blueView addSubview:dayLbl];
            [dayLbl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(blueView.mas_centerY).with.offset(0);
                make.leading.equalTo(self.mas_leading).with.offset(self.frame.size.width* 0.51);
            }];
            [blueView addSubview:hourLbl];
            [hourLbl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(blueView.mas_centerY).with.offset(0);
                make.leading.equalTo(self.mas_leading).with.offset(self.frame.size.width* 0.73);
            }];
            [blueView addSubview:minuteLbl];
            [minuteLbl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(blueView.mas_centerY).with.offset(0);
                make.leading.equalTo(self.mas_leading).with.offset(self.frame.size.width* 0.90);
            }];
            break;
        }
    }
    
    [self setNeedsDisplay];
}

@end

/**
 *  pickerView加入View，并初始化
 */
@interface BZDatePicker () <UIPickerViewDataSource, UIPickerViewDelegate> {
    
    BZDatePickerMode datePickerMode; // 默认模式为日期+时间（NDDatePickerModeDateAndTime)
    DatePickerView *datePickerView;
    NSInteger componentsCount;
    NSMutableArray *dataSourceArray;
    NSMutableArray *yearsArray;       //年选项
    NSMutableArray *monthsArray;      //月选项
    NSMutableArray *daysArray;        //日选项
    NSMutableArray *hoursArray;       //时选项
    NSMutableArray *minutesArray;     //分选项
    NSCalendar *calendar;
    NSInteger yearIndex;              //当前选中年
    NSInteger monthIndex;             //当前选中月
    NSInteger dayIndex;               //当前选中日
    NSInteger hourIndex;              //当前选中时
    NSInteger muniteIndex;            //当前选中分
}

@end



@implementation BZDatePicker

/**
 *  初始化
 *
 *  @param frame
 *  @param mode
 *  @param date
 *
 *  @return
 */
- (instancetype)initWithFrame:(CGRect)frame mode:(BZDatePickerMode)mode date:(NSDate*)date {
    
    if (self = [super initWithFrame:frame]) {
        
        [self setDate:date];
        [self setDatePickerMode:mode];
        
        datePickerView = [[DatePickerView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(frame), CODatePickerCellHeight*5)];
        datePickerView.datePickerMode = datePickerMode;
        datePickerView.dataSource = self;
        datePickerView.delegate = self;
        
        [self addSubview:datePickerView];
        
        [self initDataSource];
    }
    return self;
}

/**
 *  根据月份重新生成天数
 *
 *  @param days
 */
- (void)setdayArray:(NSInteger)days {
    
    [daysArray removeAllObjects];
    for (int i=1; i<=days; i++) {
        [daysArray addObject:[NSString stringWithFormat:@"%02d",i]];
    }
}

/**
 *  判断指定的月份有几天
 *
 *  @param year
 *  @param month
 *
 *  @return
 */
- (NSUInteger)daysInYear:(NSUInteger)year month:(NSUInteger)month {
    
    NSString *yearsStr=[NSString stringWithFormat:@"%ld",year];
    NSString *monthStr;
    if (month<10) {
        monthStr=[NSString stringWithFormat:@"%ld",month];
    }else
    {
        monthStr=[NSString stringWithFormat:@"0%ld",month];
    }
    NSString *dateFormaterStr=[NSString stringWithFormat:@"%@-%@",yearsStr,monthStr];
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSDate *date = [formatter dateFromString :dateFormaterStr];
    NSCalendar *calender = [NSCalendar currentCalendar];
    NSRange range = [calender rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return range.length;
}

#pragma mark 初始化年月日时分数据
/**
 *  初始化数据源
 */
- (void)initDataSource {
    
    NSDate *currentDate = [NSDate date];
    self.date = self.date ? : currentDate;
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |
    NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *currentComponents = [[NSDateComponents alloc] init];
    currentComponents = [calendar components:unitFlags fromDate:currentDate];
    NSInteger currentYear = currentComponents.year;
    
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    comps = [calendar components:unitFlags fromDate:self.date];
    NSInteger year = comps.year;
    NSInteger month = comps.month;
    NSInteger day = comps.day;
    NSInteger hour = comps.hour;
    NSInteger minute = comps.minute;
    
    yearIndex = (year - 1970);
    monthIndex = month -1;
    dayIndex = day - 1;
    hourIndex = hour;
    muniteIndex = minute;
    
    NSLog(@"年%d %d %d %d %d",(int)comps.year, (int)comps.month, (int)comps.day, (int)comps.hour, (int)comps.minute);
    
    //年份初始化
    yearsArray = [[NSMutableArray alloc] initWithCapacity:10];
    for (NSInteger i = 1970 ; i < currentYear + 4 ; i++) {
        [yearsArray addObject:@(i)];
    }
    
    //月份初始化
    monthsArray = [[NSMutableArray alloc] initWithCapacity:12];
    for (NSInteger i = 0; i < 12; i++) {
        [monthsArray addObject:@(i + 1)];
    }
    
    //天数初始化
    daysArray = [[NSMutableArray alloc] initWithCapacity:30];
    for (NSInteger i = 0; i < [calendar rangeOfUnit:NSCalendarUnitDay inUnit: NSCalendarUnitMonth forDate:self.date].length; i++) {
        [daysArray addObject:@(i + 1)];
    }
    
    //小时初始化
    hoursArray = [[NSMutableArray alloc]initWithCapacity:24];
    for (NSInteger i = 0; i < 24; i++) {
        [hoursArray addObject:@(i)];
    }
    
    //分钟初始化
    minutesArray = [[NSMutableArray alloc] initWithCapacity:60];
    for (NSInteger i = 0; i < 60; i++) {
        [minutesArray addObject:@(i)];
    }
    
    switch (datePickerMode) {
            //年月
        case COCDatePickerModeYearMonth: {
            dataSourceArray = [[NSMutableArray alloc]initWithObjects:yearsArray, monthsArray,nil];
            [datePickerView reloadAllComponents];
            [datePickerView selectRow:yearIndex inComponent:0 animated:YES];
            [datePickerView selectRow:monthIndex inComponent:1 animated:YES];
            break;
        }
            //时分
        case COCDatePickerModeTime: {
            dataSourceArray = [[NSMutableArray alloc]initWithObjects: hoursArray, minutesArray,nil];
            [datePickerView reloadAllComponents];
            [datePickerView selectRow:hour inComponent:0 animated:YES];
            [datePickerView selectRow:minute inComponent:1 animated:YES];
            break;
        }
            //年月日
        case COCDatePickerModeDate: {
            dataSourceArray = [[NSMutableArray alloc]initWithObjects:yearsArray, monthsArray, daysArray,nil];
            [datePickerView reloadAllComponents];
            [datePickerView selectRow:yearIndex inComponent:0 animated:YES];
            [datePickerView selectRow:monthIndex inComponent:1 animated:YES];
            [datePickerView selectRow:dayIndex inComponent:2 animated:YES];
            break;
        }
            //年月日时分
        case COCDatePickerModeDateAndTime: {
            dataSourceArray = [[NSMutableArray alloc]initWithObjects:yearsArray, monthsArray, daysArray, hoursArray, minutesArray,nil];
            [datePickerView reloadAllComponents];
            [datePickerView selectRow:yearIndex inComponent:0 animated:YES];
            [datePickerView selectRow:monthIndex inComponent:1 animated:YES];
            [datePickerView selectRow:dayIndex inComponent:2 animated:YES];
            [datePickerView selectRow:hour inComponent:3 animated:YES];
            [datePickerView selectRow:minute inComponent:4 animated:YES];
            break;
        }
        default:
            break;
    }
}


/**
 *  计算平年还是闰年
 *
 *  @param year
 *
 *  @return
 */
- (BOOL)isLeapYear:(NSInteger)year {
    
    if ((year%4 == 0 && year %100 != 0) || year%400 == 0) {
        return YES;
    }else {
        return NO;
    }
    return NO;
}


/**
 *  设置日历的模式
 *
 *  @param datePickerMode
 */
- (void)setDatePickerMode:(BZDatePickerMode)mode {
    
    switch (datePickerMode) {
            //时分
        case COCDatePickerModeYearMonth:
        case COCDatePickerModeTime:
            datePickerMode = mode;
            componentsCount = 2;
            break;
            //年月日
        case COCDatePickerModeDate:
            datePickerMode = mode;
            componentsCount = 3;
            break;
            //年月日时分
        case COCDatePickerModeDateAndTime:
            datePickerMode = mode;
            componentsCount = 5;
            break;
        default:
            datePickerMode = COCDatePickerModeTime;
            componentsCount = 2;
            break;
    }
}

#pragma mark - UIPickerViewDataSource

/**
 *  总列数
 *
 *  @param pickerView
 *
 *  @return
 */
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    
    return dataSourceArray.count;
}

/**
 *  每列的行数
 *
 *  @param pickerView
 *  @param component
 *
 *  @return
 */
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    return [dataSourceArray[component] count];
}

#pragma mark - UIPickerViewDelegate

/**
 *  title
 *
 *  @param pickerView
 *  @param row
 *  @param component
 *
 *  @return
 */
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    
    return [NSString stringWithFormat:@"第%d行",(int)row + 1];
}

/**
 *  每列每行的视图
 *
 *  @param pickerView
 *  @param row
 *  @param component
 *  @param view
 *
 *  @return
 */
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    
    UIView *indicatingView = [UIView new];
    indicatingView.backgroundColor = [UIColor clearColor];
    
    UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 5, 100, 30)];
    lbl.textColor = [UIColor blackColor];
    lbl.font = [UIFont systemFontOfSize:20];
    
    switch (datePickerMode) {
            //时分
        case COCDatePickerModeTime: {
            if ((component == 0 && hourIndex  == row) ||(component == 1 && muniteIndex  == row))
            {
                lbl.textColor = [UIColor colorWithRed:0/255.0 green:160.0/255.0 blue:232.0/255.0  alpha:1];
            }
        }
            //年月日
        case COCDatePickerModeYearMonth:
        case COCDatePickerModeDate: {
            if ((component == 0 && yearIndex == row) || (component == 1 && monthIndex == row) ||(component == 2 && dayIndex == row)){
                lbl.textColor = [UIColor colorWithRed:0/255.0 green:160.0/255.0 blue:232.0/255.0  alpha:1];
            }
        }
            //年月日时分
        case COCDatePickerModeDateAndTime: {
            if ((component == 0 && yearIndex == row) ||(component == 1 && monthIndex == row) || (component == 2 && dayIndex == row)||(component == 3 && hourIndex == row) ||(component == 4 && muniteIndex == row))
            {
                lbl.textColor = [UIColor colorWithRed:0/255.0 green:160.0/255.0 blue:232.0/255.0 alpha:1];
            }
        }
        default:
            break;
    }
    
    //不足两位的补零
    lbl.text = [self addZero:[dataSourceArray[component][row] intValue]];
    [indicatingView addSubview:lbl];
    
    //含有年月日模式下，年跟日宽度比较宽
    if (component == 0 || (datePickerMode == COCDatePickerModeDateAndTime && component == 2)) {
        indicatingView.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame) * 0.21, CODatePickerCellHeight);
    } else {
        indicatingView.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame) * 0.15, CODatePickerCellHeight);
    }
    
    return indicatingView;
}

/**
 *  行高
 *
 *  @param pickerView
 *  @param component
 *
 *  @return
 */
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    
    return CODatePickerCellHeight;
}

/**
 *  每列的宽度
 *
 *  @param pickerView
 *  @param component
 *
 *  @return
 */
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    
    switch (datePickerMode) {
            //时分
        case COCDatePickerModeYearMonth:
        case COCDatePickerModeTime: {
            if (component == 0 ) {
                return CGRectGetWidth(self.frame) * 0.21;
            }else {
                return CGRectGetWidth(self.frame) * 0.15;
            }
        }
            //年月日
        case COCDatePickerModeDate: {
            if (component == 0 || component == 2) {
                return CGRectGetWidth(self.frame) * 0.3;
            }else {
                return CGRectGetWidth(self.frame) * 0.15;
            }
        }
            //年月日时分
        case COCDatePickerModeDateAndTime: {
            if (component == 0 || component == 2) {
                return CGRectGetWidth(self.frame) * 0.21;
            }else {
                return CGRectGetWidth(self.frame) * 0.15;
            }
        }
        default:
            break;
    }
    
    return 0;
}

/**
 *  选择事件
 *
 *  @param pickerView
 *  @param row
 *  @param component
 */
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
    UIView *selectedView = [pickerView viewForRow:row forComponent:component];
    
    switch (datePickerMode) {
            //时分
        case COCDatePickerModeTime:{
            if (component==0) {
                hourIndex=row;
            }
            if (component==1) {
                muniteIndex=row;
            }
            self.date = [self getDateByIndex:-1 month:-1 day:-1 hour:hourIndex minute:muniteIndex];
            break;
        }
            //年月日
        case COCDatePickerModeYearMonth:
        case COCDatePickerModeDate:{
            if (component==0) {
                yearIndex=row;
            }
            if (component==1) {
                monthIndex=row;
            }
            if (component==2) {
                dayIndex = row;
            }
            
            self.date = [self getDateByIndex:yearIndex month:monthIndex day:dayIndex hour:-1 minute:-1];
            
            break;
        }
            //年月日时分
        case COCDatePickerModeDateAndTime:
        {
            if (component==0) {
                yearIndex=row;
            }
            if (component==1) {
                monthIndex=row;
            }
            if (component==2) {
                dayIndex = row;
            }
            if (component==3) {
                hourIndex=row;
            }
            if (component==4) {
                muniteIndex=row;
            }
            self.date = [self getDateByIndex:yearIndex month:monthIndex day:dayIndex hour:hourIndex minute:muniteIndex];
            break;
        }
        default:
            break;
    }
    
    //年月有变动时，日期要重置
    if (datePickerMode != COCDatePickerModeTime && (component == 0 || component == 1 || component == 2)) {
        
        NSInteger newdays=[self daysInYear:[yearsArray[yearIndex] intValue] month:[monthsArray[monthIndex] intValue]];
        [self setdayArray:newdays];
        
        if (newdays - 1 < dayIndex) {
            dayIndex = newdays - 1;
        }
        
        //添加日期约束
        if (datePickerMode == COCDatePickerModeDate) {
            
            self.date = [self getDateByIndex:yearIndex month:monthIndex day:dayIndex hour:-1 minute:-1];
            
            //添加时间选择范围
            [self setupDateFieldsConstraints];
        }
        
        if (datePickerMode == COCDatePickerModeDate ||
            datePickerMode == COCDatePickerModeDateAndTime) {//显示有天
            UIView *tempSelectedView = [pickerView viewForRow:dayIndex forComponent:2];
            //当前选中行颜色要变化
            UILabel *tempLbl = tempSelectedView.subviews[0];
            tempLbl.textColor = [UIColor colorWithRed:0/255.0 green:160.0/255.0 blue:232.0/255.0 alpha:1];
        }
    }
    
    //重新加载
    [pickerView reloadAllComponents];
    
    //当前选中行颜色要变化
    UILabel *lbl = selectedView.subviews[0];
    lbl.textColor = [UIColor colorWithRed:0/255.0 green:160.0/255.0 blue:232.0/255.0 alpha:1];
}

/**
 *  通过index了得时间
 *
 *  @param year
 *  @param month
 *  @param day
 *  @param hour
 *  @param minute
 *
 *  @return
 */
- (NSDate *)getDateByIndex:(NSInteger)year month:(NSInteger)month day:(NSInteger)day hour:(NSInteger)hour minute:(NSInteger)minute {
    
    NSDate *dateTemp;
    //时分
    if (year == -1) {
        NSString *strDay = [NSString stringWithFormat:@"%ld-%@-%@ %@:%@:00",(long)[self currentYear],
                            [self addZero:[self currentMonth]],[self addZero:[self currentDay]],
                            [self addZero:[hoursArray[hourIndex] intValue]],
                            [self addZero:[minutesArray[muniteIndex] intValue]]];
        dateTemp = [self getDateFromStr:strDay];
    }
    //年月日
    else if (hour == -1) {
        NSString *strDay;
        if (datePickerMode == COCDatePickerModeYearMonth) {
            strDay = [NSString stringWithFormat:@"%@-%@-01 00:00:00",yearsArray[yearIndex],[self addZero:[monthsArray[monthIndex] intValue]]];
        } else {
            strDay = [NSString stringWithFormat:@"%@-%@-%@ 00:00:00",yearsArray[yearIndex],[self addZero:[monthsArray[monthIndex] intValue]],
                      [self addZero:[daysArray[dayIndex] intValue]]];
        }
        
        dateTemp = [self getDateFromStr:strDay];
    }
    else//年月日时分
    {
        if (dayIndex < daysArray.count) {
            NSString *strDay = [NSString stringWithFormat:@"%@-%@-%@ %@:%@:00",yearsArray[yearIndex],[self addZero:[monthsArray[monthIndex] intValue]],
                                [self addZero:[daysArray[dayIndex] intValue]],
                                [self addZero:[hoursArray[hourIndex] intValue]],
                                [self addZero:[minutesArray[muniteIndex] intValue]]];
            dateTemp = [self getDateFromStr:strDay];
        }
        
    }
    return dateTemp;
}

- (void)setupDateFieldsConstraints {
    
    if (self.date && datePickerMode == COCDatePickerModeDate) {
        //确保最小时间小于最大时间
        if(self.minimumDate && self.maximumDate &&
           ([self.maximumDate timeIntervalSince1970] < [self.minimumDate timeIntervalSince1970])) {
            
            NSDate *tempDate = self.maximumDate;
            self.maximumDate = self.minimumDate;
            self.minimumDate = tempDate;
        }
        
        if (self.minimumDate && ([self.date timeIntervalSince1970] < [self.minimumDate timeIntervalSince1970])) {
            
            NSCalendar *calendar = [NSCalendar currentCalendar];
            NSDateComponents *components = [calendar components:(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay)
                                                       fromDate:self.minimumDate];
            yearIndex = [components year]-1970;
            monthIndex = [components month]-1;
            dayIndex = [components day]-1;
        } else if (self.maximumDate && ([self.date timeIntervalSince1970] > [self.maximumDate timeIntervalSince1970])) {
            
            NSCalendar *calendar = [NSCalendar currentCalendar];
            NSDateComponents *components = [calendar components:(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay)
                                                       fromDate:self.maximumDate];
            yearIndex = [components year]-1970;
            monthIndex = [components month]-1;
            dayIndex = [components day]-1;
        }
        //重置选中日期后更新数据
        NSInteger newdays=[self daysInYear:[yearsArray[yearIndex] intValue] month:[monthsArray[monthIndex] intValue]];
        [self setdayArray:newdays];
        
        [datePickerView reloadAllComponents];
        [datePickerView selectRow:yearIndex inComponent:0 animated:YES];
        [datePickerView selectRow:monthIndex inComponent:1 animated:YES];
        [datePickerView selectRow:dayIndex inComponent:2 animated:YES];
        
        self.date = [self getDateByIndex:yearIndex month:monthIndex day:dayIndex hour:-1 minute:-1];
    }
}

/**
 *  取当前年
 *
 *  @return
 */
- (NSInteger)currentYear {
    
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    NSInteger year = [dateComponent year];
    return year;
}

/**
 *  取当前月
 *
 *  @return
 */
- (NSInteger)currentMonth {
    
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    NSInteger month = [dateComponent month];
    return month;
}

/**
 *  取当前日
 *
 *  @return
 */
- (NSInteger)currentDay {
    
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    NSInteger day = [dateComponent day];
    return day;
}

/**
 *  字符串转日期
 *
 *  @param strDay
 *
 *  @return
 */
- (NSDate *)getDateFromStr:(NSString*)strDay {
    
    NSDateFormatter *inputFormatter= [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [inputFormatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
    NSDate *inputDate = [inputFormatter dateFromString:strDay];
    //    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    //    NSInteger interval = [zone secondsFromGMTForDate:inputDate];
    //    NSDate *localeDate = [inputDate  dateByAddingTimeInterval: interval];
    return inputDate;
}

/**
 *  补零操作
 *
 *  @param index
 *
 *  @return
 */
- (NSString*)addZero:(int)index {
    
    NSString *temp;
    if (index < 10) {
        temp = [NSString stringWithFormat:@"0%ld",(long)index ];
    }else
    {
        temp = [NSString stringWithFormat:@"%ld",(long)index ];
    }
    return temp;
}


@end
